<?php

class MsggSmtp extends MsggChannelBase
{
    const MAILER_PORT = 25;
    const MAILER_CHARSET = 'UTF-8';
    const MAILER_SMTPAUTH = true;
    const MAILER_IS_SSL = true;
    const MAILER_IS_HTML = true;
    const MAILER_CLASS = 'application.extensions.mailer.EMailer';

    const ERROR_CODE_FAIL = 1;
    const ERROR_MSG_FAIL = 'send fail,please contact admin';

    private static $_conf = array();

    public static function mail($params, $conf = array())
    {
        self::$_conf = $conf;
        $result = array('code' => 0, 'msg' => '', 'data' => array());
        try {
            $mailer = Yii::createComponent(array(
                'class' => static::getConf('class', self::MAILER_CLASS),
                'Host' => static::getConf('host'),
                'Port' => static::getConf('port', self::MAILER_PORT),
                'CharSet' => static::getConf('charset', self::MAILER_CHARSET),
                'Is_SSL' => static::getConf('is_ssl', self::MAILER_IS_SSL),
                'SMTPAuth' => static::getConf('smtp_auth', self::MAILER_SMTPAUTH),
                'Username' => static::getConf('username'),
                'Password' => static::getConf('password'),
            ));
            $mailer->isSMTP();
            //set from
            $mailer->SetFrom(static::getConf('from'), $params['from']);
            //set to
            $mailer->clearAddresses();
            foreach ($params['address'] as $address) {
                $mailer->AddAddress($address);
            }
            //set title
            $mailer->Subject = "=?utf-8?B?" . base64_encode($params['title']) . "?=";
            //set content
            if (array_key_exists('ishtml', $params) && ($params['ishtml'] == false)) {
                $mailer->IsHTML(false);
            } else {
                $mailer->IsHTML(true);
            }
            $mailer->Body = empty($params['content']) ? '' : $params['content'];
            //send,try 3 times
            $try = self::getConf('try', 2);
            while ($try) {
                $try--;
                if ($mailer->Send()) {
                    break;
                }
                if (!$try) {
                    throw new Exception($mailer->ErrorInfo, self::ERROR_CODE_FAIL);
                }
            }
        } catch (Exception $e) {
            if ($e->getCode() != self::ERROR_CODE_FAIL) {
                $result['code'] = self::ERROR_CODE_FAIL;
                $result['msg'] = self::ERROR_MSG_FAIL . ':' . $e->getMessage();
            } else {
                $result['code'] = $e->getCode();
                $result['msg'] = $e->getMessage();
            }
        }
        $result['ext']['class']=self::class;
        return $result;
    }

    public static function getConf($name, $default = null)
    {
        return isset(static::$_conf[$name]) ? static::$_conf[$name] : $default;
    }

}